/**
 * 技能效果注册表
 * 管理所有技能效果处理器的注册和查找
 */

import { ISkillEffectHandler, SkillEffectType } from './SkillEffectTypes';
import { ServiceLogger } from '../../../../infrastructure/logging/UnifiedLogger';

/**
 * 技能效果注册表
 */
export class SkillEffectRegistry {
    private logger: ServiceLogger;
    private handlers = new Map<SkillEffectType, ISkillEffectHandler>();
    private handlersByPriority: ISkillEffectHandler[] = [];

    constructor() {
        this.logger = new ServiceLogger('SkillEffectRegistry');
    }

    /**
     * 注册效果处理器
     */
    registerHandler(handler: ISkillEffectHandler): void {
        // 检查是否已存在该类型的处理器
        if (this.handlers.has(handler.effectType)) {
            this.logger.warn(`Overwriting existing handler for type: ${handler.effectType}`);
        }

        // 注册处理器
        this.handlers.set(handler.effectType, handler);
        
        // 重新排序优先级列表
        this.rebuildPriorityList();

        this.logger.info(`Effect handler registered: ${handler.effectType}`, {
            metadata: { 
                effectType: handler.effectType,
                priority: handler.priority,
                totalHandlers: this.handlers.size
            }
        });
    }

    /**
     * 获取效果处理器
     */
    getHandler(effectType: SkillEffectType): ISkillEffectHandler | null {
        return this.handlers.get(effectType) || null;
    }

    /**
     * 获取所有处理器
     */
    getAllHandlers(): ISkillEffectHandler[] {
        return Array.from(this.handlers.values());
    }

    /**
     * 按优先级获取处理器
     */
    getHandlersByPriority(): ISkillEffectHandler[] {
        return [...this.handlersByPriority];
    }

    /**
     * 移除处理器
     */
    removeHandler(effectType: SkillEffectType): boolean {
        const removed = this.handlers.delete(effectType);
        if (removed) {
            this.rebuildPriorityList();
            this.logger.info(`Effect handler removed: ${effectType}`);
        }
        return removed;
    }

    /**
     * 检查是否存在处理器
     */
    hasHandler(effectType: SkillEffectType): boolean {
        return this.handlers.has(effectType);
    }

    /**
     * 获取处理器数量
     */
    getHandlerCount(): number {
        return this.handlers.size;
    }

    /**
     * 获取支持的效果类型列表
     */
    getSupportedEffectTypes(): SkillEffectType[] {
        return Array.from(this.handlers.keys());
    }

    /**
     * 验证所有处理器
     */
    validateAllHandlers(): { valid: boolean; errors: string[] } {
        const errors: string[] = [];
        
        for (const [effectType, handler] of this.handlers) {
            try {
                // 检查处理器基本属性
                if (!handler.effectType) {
                    errors.push(`Handler for ${effectType} missing effectType`);
                }
                if (typeof handler.priority !== 'number') {
                    errors.push(`Handler for ${effectType} missing or invalid priority`);
                }
                if (typeof handler.canHandle !== 'function') {
                    errors.push(`Handler for ${effectType} missing canHandle method`);
                }
                if (typeof handler.execute !== 'function') {
                    errors.push(`Handler for ${effectType} missing execute method`);
                }
                if (typeof handler.validateConfig !== 'function') {
                    errors.push(`Handler for ${effectType} missing validateConfig method`);
                }
                if (typeof handler.getDescription !== 'function') {
                    errors.push(`Handler for ${effectType} missing getDescription method`);
                }
            } catch (error) {
                errors.push(`Handler for ${effectType} validation failed: ${(error as Error).message}`);
            }
        }

        const valid = errors.length === 0;
        if (valid) {
            this.logger.info('All handlers validated successfully');
        } else {
            this.logger.error('Handler validation failed', { metadata: { errors } });
        }

        return { valid, errors };
    }

    /**
     * 获取注册表统计信息
     */
    getRegistryStats(): {
        totalHandlers: number;
        handlersByType: Record<string, number>;
        averagePriority: number;
        priorityRange: { min: number; max: number };
    } {
        const handlers = this.getAllHandlers();
        const handlersByType: Record<string, number> = {};
        let totalPriority = 0;
        let minPriority = Infinity;
        let maxPriority = -Infinity;

        for (const handler of handlers) {
            // 统计类型分布
            const typeCategory = this.categorizeEffectType(handler.effectType);
            handlersByType[typeCategory] = (handlersByType[typeCategory] || 0) + 1;
            
            // 统计优先级
            totalPriority += handler.priority;
            minPriority = Math.min(minPriority, handler.priority);
            maxPriority = Math.max(maxPriority, handler.priority);
        }

        return {
            totalHandlers: handlers.length,
            handlersByType,
            averagePriority: handlers.length > 0 ? totalPriority / handlers.length : 0,
            priorityRange: {
                min: minPriority === Infinity ? 0 : minPriority,
                max: maxPriority === -Infinity ? 0 : maxPriority
            }
        };
    }

    /**
     * 清空所有处理器
     */
    clear(): void {
        const count = this.handlers.size;
        this.handlers.clear();
        this.handlersByPriority = [];
        
        this.logger.info(`Registry cleared: ${count} handlers removed`);
    }

    /**
     * 批量注册处理器
     */
    registerHandlers(handlers: ISkillEffectHandler[]): void {
        for (const handler of handlers) {
            this.registerHandler(handler);
        }
        
        this.logger.info(`Batch registered ${handlers.length} handlers`);
    }

    /**
     * 查找处理器（支持模糊匹配）
     */
    findHandlers(pattern: string): ISkillEffectHandler[] {
        const results: ISkillEffectHandler[] = [];
        const lowerPattern = pattern.toLowerCase();
        
        for (const [effectType, handler] of this.handlers) {
            if (effectType.toLowerCase().includes(lowerPattern)) {
                results.push(handler);
            }
        }
        
        return results;
    }

    /**
     * 获取处理器信息
     */
    getHandlerInfo(effectType: SkillEffectType): {
        exists: boolean;
        handler?: ISkillEffectHandler;
        priority?: number;
        category?: string;
    } {
        const handler = this.handlers.get(effectType);
        
        if (!handler) {
            return { exists: false };
        }
        
        return {
            exists: true,
            handler,
            priority: handler.priority,
            category: this.categorizeEffectType(effectType)
        };
    }

    // ==================== 私有方法 ====================

    /**
     * 重建优先级列表
     */
    private rebuildPriorityList(): void {
        this.handlersByPriority = Array.from(this.handlers.values())
            .sort((a, b) => b.priority - a.priority); // 高优先级在前
    }

    /**
     * 对效果类型进行分类
     */
    private categorizeEffectType(effectType: SkillEffectType): string {
        if (effectType.includes('damage')) {
            return 'damage';
        } else if (effectType.includes('heal') || effectType === SkillEffectType.REGENERATION) {
            return 'healing';
        } else if (effectType.includes('buff') || effectType.includes('debuff')) {
            return 'buff';
        } else if (effectType.includes('shield')) {
            return 'defense';
        } else if (effectType.includes('attribute') || effectType.includes('modify')) {
            return 'attribute';
        } else if (effectType.includes('mana') || effectType.includes('energy')) {
            return 'resource';
        } else if (effectType === SkillEffectType.STUN || 
                   effectType === SkillEffectType.SILENCE || 
                   effectType === SkillEffectType.ROOT || 
                   effectType === SkillEffectType.BLIND) {
            return 'control';
        } else if (effectType.includes('teleport') || 
                   effectType.includes('summon') || 
                   effectType.includes('swap')) {
            return 'special';
        } else if (effectType.includes('permanent') || effectType.includes('upgrade')) {
            return 'enhancement';
        } else {
            return 'other';
        }
    }
}
